import com.jcraft.jsch.*;
import java.io.*;

public class SshHandler {
	Session session = null;
	
	public void initSession(String sshUser, String sshPwd, String sshHost, int sshPort) {
		try {
			JSch.setConfig("StrictHostKeyChecking", "no");
			JSch jsch = new JSch();
			
			//Connect with SSH session.
			session = jsch.getSession(sshUser, sshHost, sshPort);
			session.setPassword(sshPwd);
			session.connect();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void disconnectSession() {
		try {
			if (session != null && session.isConnected())
				session.disconnect();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public ExecResult execCommand(String cmdStr) throws IllegalStateException {
		if (!session.isConnected())
			throw new IllegalStateException("Must be connected to an SSH session. Call initSession() to establish connection.");
		
		ExecResult result = new ExecResult();
		result.output = "";
		
		try {
			//Open an 'exec' channel to execute commands over SSH.
			Channel channel = session.openChannel("exec");
			
			// Set the command to execute and the IO streams.
			((ChannelExec)channel).setCommand(cmdStr);
			channel.setInputStream(null);
			((ChannelExec)channel).setErrStream(System.err);
			InputStream in = channel.getInputStream();
			
			// Connect to the channel.
			channel.connect();
			
			// Get the output and return value of the command.
			final int arr_Size = 1024;
			byte[] tmp = new byte[arr_Size];
			while(true) {
				while(in.available() > 0) {
					int i = in.read(tmp, 0, arr_Size);
					if (i < 0) break;
					result.output += new String(tmp, 0, i);
				}
				if (channel.isClosed()) {
					result.returnValue = channel.getExitStatus();
					break;
				}
				try {
					Thread.sleep(1000);
				}
				catch(Exception e) {
					e.printStackTrace();
				}
			}
			
			channel.disconnect();
		}
		catch (Exception e) {
			e.printStackTrace();
		}
			
		return result;
	}
	
	public class ExecResult {
		public int returnValue;
		public String output;
	}
}